import com.dmotiko.general.*
import com.dmotiko.util.*
import mx.utils.Delegate

class PhotoSlider
extends BaseClip {
	
	public static var FIRST_PHOTO_LOADED:String = "photoslider_firstphotoloaded";
	private static var FRAMES_TIMER:Number = 90;
	
	private var root:PhotoSlider;
	private var mcSlideShow;
	private var mcSlideShow2;
	private var mcl:MovieClipLoader;
	private var mcLoader:LoaderClip;
	
	private var bSlideShow:Boolean;
	private var aSlides:Array;
	private var nCount:Number;
	private var bFirst:Boolean;
	private var lastSlide:MovieClip;
	
	private var timer:Function;
	private var timerController:MovieClip;
	
	private function PhotoSlider() {
		super();
		
		bSlideShow = true;
		
		if (!mcSlideShow) mcSlideShow = this.createEmptyMovieClip("mcSlideShow", this.getNextHighestDepth());
		if (!mcSlideShow2) mcSlideShow2 = this.createEmptyMovieClip("mcSlideShow2", this.getNextHighestDepth());
		
		root = this;
		bFirst = false;
		aSlides = new Array();
		
		mcl = new MovieClipLoader();
		MovieEffects.timer();
	}
		
	private function startSlider():Void {
		mcl.addListener(this);
		nCount = 0;
		this.timerController.stopEffect();
		var nextSlide = (mcSlideShow == lastSlide) ? mcSlideShow2 : mcSlideShow;
		mcl.loadClip(aSlides[nCount], nextSlide);
	}
		
	private function onLoadStart(target){
		if(!bFirst && mcLoader) {
			mcLoader.addEventListener( BaseClipEvent.CHANGED, Delegate.create(this, loadComplete) );	
		} else if(!bFirst) {
			loadComplete();
		}
	}
	
	private function onLoadProgress(target, loaded, total){
		if(!bFirst && mcLoader) {
			var p = ((loaded/total)*100);
			p = Math.round(p);
			mcLoader.setPos(p);	
		}
	}
	
	private function onLoadInit(target){
		if(!bFirst) {
			bFirst = true;
			target._alpha = 0;
			lastSlide = target;
								
		} else {
			lastSlide.fadeOut( { rate: 7 });
			lastSlide = target;
			target._alpha = 0;
			target.fadeIn( { bind: this, listener: photoShowEnd, rate: 7 } );
		}
	}
	
	private function loadComplete(evnt, data){
		MovieEffects.fadeIn();
		MovieEffects.fadeOut();
		mcSlideShow._alpha = 0;
		mcSlideShow.fadeIn( { bind: this, listener: firstPhotoShowEnd, rate: 7 } );
	}
	
	private function firstPhotoShowEnd(){
		photoShowEnd();
	}
	private function photoShowEnd(){
		if( aSlides.length <= 1) return;
		else this.timerController.stopEffect();
		
		if(bSlideShow){
			this.timerController = this.timer( { frames: FRAMES_TIMER, bind: this, listener: nextPhoto } );
		}
	}
	
	private function nextPhoto(){
		var nextSlide = (mcSlideShow == lastSlide) ? mcSlideShow2 : mcSlideShow;
		nCount++;
		if(nCount > aSlides.length - 1) nCount = 0;
		mcl.loadClip(aSlides[nCount], nextSlide);
	}
	
}